<template>
  <div class="fetch-hook-demo p-4">
    <div class="space-y-6">
      <!-- JSONPlaceholder API 演示 -->
      <div class="fetch-section">
        <h4 class="fetch-title">JSONPlaceholder API 演示</h4>
        <div class="space-y-3">
          <div class="api-controls">
            <select v-model="selectedEndpoint" class="endpoint-select">
              <option value="posts">文章 (Posts)</option>
              <option value="users">用户 (Users)</option>
              <option value="comments">评论 (Comments)</option>
              <option value="albums">相册 (Albums)</option>
            </select>
            <button
              @click="fetchData.refresh()"
              :disabled="fetchData.loading.value"
              class="refresh-button"
            >
              {{ fetchData.loading.value ? '加载中...' : '刷新数据' }}
            </button>
          </div>

          <div class="api-status">
            <div class="status-item">
              <span class="status-label">状态:</span>
              <span :class="['status-badge', getStatusClass()]">
                {{ getStatusText() }}
              </span>
            </div>
            <div class="status-item">
              <span class="status-label">URL:</span>
              <span class="status-url">{{ currentUrl }}</span>
            </div>
          </div>

          <div class="api-result">
            <div v-if="fetchData.loading.value" class="loading-state">
              <div class="loading-spinner"></div>
              <div>正在加载数据...</div>
            </div>

            <div v-else-if="fetchData.error.value" class="error-state">
              <div class="error-icon">❌</div>
              <div class="error-message">
                {{ fetchData.error.value.message }}
              </div>
              <button @click="fetchData.execute()" class="retry-button">重试</button>
            </div>

            <div v-else-if="fetchData.data.value" class="success-state">
              <div class="data-header">
                <span>数据 ({{ fetchData.data.value.length }} 条)</span>
                <button @click="toggleDataView" class="view-toggle">
                  {{ showRawData ? '显示格式化' : '显示原始数据' }}
                </button>
              </div>

              <div v-if="showRawData" class="raw-data">
                <pre>{{ JSON.stringify(fetchData.data.value.slice(0, 3), null, 2) }}</pre>
              </div>

              <div v-else class="formatted-data">
                <div
                  v-for="(item, index) in fetchData.data.value.slice(0, 5)"
                  :key="item.id || index"
                  class="data-item"
                >
                  <template v-if="selectedEndpoint === 'posts'">
                    <div class="item-title">{{ item.title }}</div>
                    <div class="item-content">{{ item.body?.slice(0, 100) }}...</div>
                  </template>

                  <template v-else-if="selectedEndpoint === 'users'">
                    <div class="item-title">{{ item.name }}</div>
                    <div class="item-content">{{ item.email }} | {{ item.website }}</div>
                  </template>

                  <template v-else>
                    <div class="item-title">{{ item.name || item.title || `项目 ${item.id}` }}</div>
                    <div class="item-content">{{ item.body || item.email || '详细信息...' }}</div>
                  </template>
                </div>
              </div>
            </div>

            <div v-else class="empty-state">点击"刷新数据"开始获取数据</div>
          </div>
        </div>
      </div>

      <!-- 错误处理演示 -->
      <div class="fetch-section">
        <h4 class="fetch-title">错误处理演示</h4>
        <div class="space-y-3">
          <div class="error-demo-controls">
            <button @click="fetchValidData" class="demo-button success">获取正常数据</button>
            <button @click="fetch404Error" class="demo-button error">模拟 404 错误</button>
            <button @click="fetchNetworkError" class="demo-button warning">模拟网络错误</button>
          </div>

          <div class="error-result">
            <div v-if="errorDemo.loading.value" class="loading-state small">
              <div class="loading-spinner small"></div>
              <span>请求中...</span>
            </div>

            <div v-else-if="errorDemo.error.value" class="error-display">
              <div class="error-title">请求失败</div>
              <div class="error-details">
                <div class="error-type">错误类型: {{ errorDemo.error.value.message }}</div>
                <div class="error-timestamp">时间: {{ new Date().toLocaleString() }}</div>
              </div>
            </div>

            <div v-else-if="errorDemo.data.value" class="success-display">
              <div class="success-title">请求成功</div>
              <div class="success-data">
                获取到
                {{ Array.isArray(errorDemo.data.value) ? errorDemo.data.value.length : 1 }} 条数据
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Hook 说明 -->
    <div class="mt-6 p-4 bg-purple-50 border border-purple-200 rounded">
      <h5 class="text-sm font-medium text-purple-800 mb-2">🌐 useFetch Hook 特性</h5>
      <ul class="text-xs text-purple-700 space-y-1">
        <li>• <strong>自动管理状态</strong>: loading、error、data 状态自动维护</li>
        <li>• <strong>灵活配置</strong>: 支持立即执行、URL 变化重新请求等选项</li>
        <li>• <strong>错误处理</strong>: 内置错误处理机制，统一错误状态管理</li>
        <li>• <strong>手动控制</strong>: 提供 execute、refresh 方法手动触发请求</li>
        <li>• <strong>TypeScript 支持</strong>: 完整的类型定义和泛型支持</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useFetch } from '@/hooks/useFetch'

// JSONPlaceholder API 演示
const selectedEndpoint = ref('posts')
const showRawData = ref(false)

const currentUrl = computed(() => `https://jsonplaceholder.typicode.com/${selectedEndpoint.value}`)

const fetchData = useFetch(() => currentUrl.value, { immediate: false })

const getStatusClass = () => {
  if (fetchData.loading.value) return 'status-loading'
  if (fetchData.error.value) return 'status-error'
  if (fetchData.data.value) return 'status-success'
  return 'status-idle'
}

const getStatusText = () => {
  if (fetchData.loading.value) return '加载中'
  if (fetchData.error.value) return '请求失败'
  if (fetchData.data.value) return '请求成功'
  return '未开始'
}

const toggleDataView = () => {
  showRawData.value = !showRawData.value
}

// 监听 endpoint 变化
watch(selectedEndpoint, () => {
  fetchData.execute()
})

// 错误处理演示
const errorDemo = useFetch('', { immediate: false })

const fetchValidData = () => {
  const validFetch = useFetch('https://jsonplaceholder.typicode.com/posts/1', { immediate: false })
  validFetch.execute().then(() => {
    errorDemo.data.value = validFetch.data.value
    errorDemo.error.value = null
    errorDemo.loading.value = false
  })
  errorDemo.loading.value = true
}

const fetch404Error = () => {
  errorDemo.loading.value = true
  errorDemo.data.value = null

  fetch('https://jsonplaceholder.typicode.com/posts/999999')
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: 资源未找到`)
      }
      return response.json()
    })
    .catch((error) => {
      errorDemo.error.value = error
      errorDemo.loading.value = false
    })
}

const fetchNetworkError = () => {
  errorDemo.loading.value = true
  errorDemo.data.value = null

  fetch('https://invalid-domain-that-does-not-exist.com/api').catch((error) => {
    errorDemo.error.value = new Error('网络连接失败')
    errorDemo.loading.value = false
  })
}
</script>

<style scoped lang="scss">
.fetch-hook-demo {
  @apply bg-gray-50;
}

.fetch-section {
  @apply p-4 bg-white rounded-lg border border-gray-200;
}

.fetch-title {
  @apply text-base font-semibold text-gray-800 mb-4 pb-2 border-b border-gray-200;
}

.api-controls {
  @apply flex space-x-3;
}

.endpoint-select {
  @apply px-3 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent;
}

.refresh-button {
  @apply px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed;
}

.api-status {
  @apply space-y-2 p-3 bg-gray-100 rounded;
}

.status-item {
  @apply flex items-center space-x-2 text-sm;
}

.status-label {
  @apply font-medium text-gray-600;
}

.status-badge {
  @apply px-2 py-1 rounded text-xs font-medium;

  &.status-idle {
    @apply bg-gray-100 text-gray-700;
  }

  &.status-loading {
    @apply bg-yellow-100 text-yellow-700;
  }

  &.status-success {
    @apply bg-green-100 text-green-700;
  }

  &.status-error {
    @apply bg-red-100 text-red-700;
  }
}

.status-url {
  @apply font-mono text-xs bg-white px-2 py-1 rounded border;
}

.api-result {
  @apply min-h-[200px] p-4 border border-gray-200 rounded-lg;
}

.loading-state {
  @apply flex flex-col items-center justify-center space-y-3 text-gray-600;

  &.small {
    @apply flex-row space-y-0 space-x-2;
  }
}

.loading-spinner {
  @apply w-8 h-8 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin;

  &.small {
    @apply w-4 h-4 border-2;
  }
}

.error-state {
  @apply flex flex-col items-center justify-center space-y-3 text-red-600;
}

.error-icon {
  @apply text-3xl;
}

.error-message {
  @apply text-center;
}

.retry-button {
  @apply px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600;
}

.success-state {
  @apply space-y-3;
}

.data-header {
  @apply flex justify-between items-center;
}

.view-toggle {
  @apply px-3 py-1 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300;
}

.raw-data {
  @apply bg-gray-900 text-green-400 p-3 rounded text-xs font-mono overflow-auto max-h-64;
}

.formatted-data {
  @apply space-y-2;
}

.data-item {
  @apply p-3 bg-gray-50 rounded border;
}

.item-title {
  @apply font-medium text-gray-800 mb-1;
}

.item-content {
  @apply text-sm text-gray-600;
}

.empty-state {
  @apply text-center text-gray-500 py-8;
}

.error-demo-controls {
  @apply flex flex-wrap gap-2;
}

.demo-button {
  @apply px-4 py-2 rounded font-medium transition-colors;

  &.success {
    @apply bg-green-500 text-white hover:bg-green-600;
  }

  &.error {
    @apply bg-red-500 text-white hover:bg-red-600;
  }

  &.warning {
    @apply bg-orange-500 text-white hover:bg-orange-600;
  }
}

.error-result {
  @apply p-3 border border-gray-200 rounded-lg min-h-[100px];
}

.error-display {
  @apply text-red-600;
}

.error-title {
  @apply font-medium mb-2;
}

.error-details {
  @apply space-y-1 text-sm;
}

.success-display {
  @apply text-green-600;
}

.success-title {
  @apply font-medium mb-2;
}
</style>
